package com.example.wx.controller;

import com.example.wx.util.JsonResult;
import com.example.wx.domain.Account;
import com.example.wx.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;


@Controller
@RequestMapping("/account")
@SessionAttributes("loginAccount")
public class AccountController {
    @Autowired
    Account account;
    @Autowired
    AccountService accountService;

    @GetMapping("/viewLogin")
    public String viewLogin(){
        return "account/login";
    }

//    @GetMapping("/login")
//    public JsonResult<Account> login(@RequestAttribute("username")String username,
//                                     @RequestAttribute("password")String password,
//                                     Model model) throws Exception {
//        Account loginAccount = account;
//        loginAccount = accountService.login(username,password);
//        if(loginAccount == null){
//            return new JsonResult<>("1",accountService.getMsg());
//        }
//        model.addAttribute("loginAccount",loginAccount);
//        System.out.println(new JsonResult<>(loginAccount,accountService.getMsg()));
//        return new JsonResult<>(loginAccount,accountService.getMsg());
//    }

    @GetMapping("/login")
    public String login(@RequestParam("username")String username,
                        @RequestParam("password")String password,
                        HttpSession session){

        if (username.equals("j2ee")&&password.equals("j2ee")){
            session.setAttribute("username", username);
            System.out.println("login successful");
            return "index";
        } else {
            return "common/error";
        }

    }

    @RequestMapping("/register")
    @ResponseBody
    public JsonResult<Account> register(@RequestAttribute("username")String username, @RequestAttribute("password")String password){
        //将注册中的用户信息填入account
        account.setUsername(username);
        account.setPassword(password);
        //下面继续填入需要添加的用户注册信息
        //。。。。。。

        if(accountService.registerAdmin(account)){  //注册成功
            return new JsonResult<>(account,accountService.getMsg());
        }else { //注册失败
            return new JsonResult<>("2",accountService.getMsg());
        }
    }


}
